package com.json.servlet;

import java.io.*;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.*;



public class JsonServlet extends HttpServlet {

	 
	private static final long serialVersionUID = -5117794813343721264L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("get method!");
		this.doProcess(req, resp);
		
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		System.out.println("post method!");
		this.doProcess(req, resp);
		
	}
	
	private void doProcess(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		if ("validate".equals(req.getParameter("validate"))) {
			this.validate(req, resp);
			return;
		}
		
		
		System.out.println("abcd:" + req.getParameter("ss"));
		//resp.setContentType("application/json; charset=UTF-8");
		PrintWriter out = resp.getWriter();
		out.println(this.getJson());
		out.close();
	}
	
	private void validate(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		System.out.println("validate..." + req.getParameter("enName"));
		Map<String,Object> jsonMessage = new HashMap<String,Object>();
		jsonMessage.put("result", false);
		if ("kitty".equals(req.getParameter("enName"))) {
			jsonMessage.put("result", true);
		}
		resp.getWriter().println(JSONObject.fromObject(jsonMessage));
		resp.getWriter().close();
	}
	
	
	
	private String getJson() {
		List<String> jsonList = new ArrayList<String>();//Arrays.asList("first","second","third","fourth","fifth");
		jsonList.add("first");
		jsonList.add("second");
		jsonList.add("third");
		
		JSONArray jsonArray = JSONArray.fromObject(jsonList);
		
		//System.out.println(jsonArray);
		/*
		Map<String,String> first = new HashMap<String,String>();
		first.put("mosquito_id", "1");
		first.put("mosquito_name", "abcde");
		Map<String,String> second = new HashMap<String,String>();
		second.put("mosquito_id", "2");
		second.put("mosquito_name", "ffffff");
		Map<String,String> third = new HashMap<String,String>();
		third.put("mosquito_id", "3");
		third.put("mosquito_name", "gggggg");
		List<Map<String,String>> mapList = Arrays.asList(first,second,third);
		
		
		jsonArray = JSONArray.fromObject(mapList);
		*/
		
		return jsonArray.toString();
	}
	

}
